package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工控制器
 * @author ghy
 * @version v1.0
 * create on 2022/11/15 14:58
 */
@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable(name = "id") Long id){
        Employee employee = employeeService.getById(id);
        if(employee == null) {
            return R.error("查无此员工");
        }
        return R.success(employee);
    }



    @PutMapping
    public R updateStatus(HttpSession session, @RequestBody Employee employee){
        log.warn("{}", employee);
        //UpdateWrapper<Employee> updateWrapper = Wrappers.<Employee>update()
        //        .set("status", employee.getStatus())
        //        .set("update_time", LocalDateTime.now())
        //        .set("update_user", (Long)session.getAttribute("employee"))
        //        .eq("id", employee.getId());
                // update employee set status = ?, update_time = ? where id = ?
        //employeeService.update(updateWrapper);
        log.error("当前线程ID:{}", Thread.currentThread().getId());
        return employeeService.modify(employee, (Long) session.getAttribute("employee"));
    }


    /**
     * 分页条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name){
        IPage<Employee> ipage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Employee> lqw = Wrappers.lambdaQuery();
        //1.根据名称去查询
        //name like ?
        lqw.like(StringUtils.isNotBlank(name),Employee::getName, name);
        //2.根据更新时间排序，倒序
        lqw.orderByDesc(Employee::getUpdateTime);

        employeeService.page(ipage, lqw);

        List<Employee> emps = ipage.getRecords().stream()
                .map(item -> {
                    //item : 正在迭代的对象，在这里代表就是员工
                    item.setPassword("");
                    return item;
                }).collect(Collectors.toList());
        ipage.setRecords(emps);

        return R.success(ipage);
    }

    /**
     * 新增员工
     * @param session
     * @param employee
     * @return
     */
    @PostMapping
    public R add(HttpSession session, @RequestBody Employee employee){
        Long employeeId = (Long) session.getAttribute("employee");
        return employeeService.add(employee, employeeId);
    }

    /**
     * 退出
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.removeAttribute("employee");
        return R.success("员工退出成功");
    }

    /**
     * 登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody Employee employee){

        if(employee == null) {
            return R.error("参数有误");
        }
        //1. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2. 根据页面提交的用户名username查询数据库中员工数据信息
        //2.1 封装查询条件对象
        LambdaQueryWrapper<Employee> lqw = Wrappers.<Employee>lambdaQuery();
        //2.2 WHERE username = ?
        //  Employee::getUsername  --> 类中的username属性  --> 映射到表中的username字段
        lqw.eq(Employee::getUsername, employee.getUsername());  //WHERE username = ?
        //2.3 SELECT * FROM employee WHERE (username = ?)
        Employee emp = employeeService.getOne(lqw);

        //3. 如果没有查询到, 则返回登录失败结果
        if(emp == null) {
            return R.error("用户不存在");
        }
        //4. 密码比对，如果不一致, 则返回登录失败结果
        if(!md5Password.equals(emp.getPassword())) {
            return R.error("用户名或者密码错误");
        }

        //5. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(!emp.getStatus().equals(1)) {
            return R.error("用户状态异常");
        }

        //6. 登录成功，将员工id存入Session, 并返回登录成功结果
        session.setAttribute("employee", emp.getId());
        emp.setPassword("");
        return R.success(emp);
    }

}
